package cn.snowheart.ssm.web;

import cn.snowheart.ssm.pojo.Employee;
import cn.snowheart.ssm.service.IEmployeeService;
import cn.snowheart.ssm.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuwanxiang
 * @version 2018/4/22
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @RequestMapping("/list.json")
    public Object list() {
        return ResponseUtil.success(employeeService.list());
    }

    @RequestMapping("/employees.json")
    public Object getEmployeePage(@RequestParam("pageNo") Integer pageNo) {
        return ResponseUtil.success(employeeService.getEmployeePage(pageNo));
    }

    @RequestMapping("/checkuser.json")
    public Object checkUser(@RequestParam("empName") String empName) {
        return ResponseUtil.success(employeeService.checkUser(empName));
    }

    @RequestMapping("/insert.json")
    public Object insert(@Valid Employee employee, BindingResult result) {

        if (result.hasErrors()) {
            // 有错误
            Map map = new HashMap<>();
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                map.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            return ResponseUtil.error(map);
        } else {
            // save
            employeeService.saveEmployee(employee);
            return ResponseUtil.success();
        }

    }

    @RequestMapping(value = "/employee.json/{id}",method = RequestMethod.GET)
    public Object getEmployeeById(@PathVariable Integer id) {
        return ResponseUtil.success(employeeService.getEmployeeById(id));
    }

    @RequestMapping(value = "/employee.json/{id}",method = RequestMethod.PUT)
    public Object updateEmployee(Employee employee, @PathVariable Integer id) {
        employee.setEmpId(id);
        employeeService.updateEmployee(employee);
        return ResponseUtil.success();
    }

    @RequestMapping(value = "/employee.json/{ids}",method = RequestMethod.DELETE)
    public Object deleteEmployee(@PathVariable String ids) {
        employeeService.deleteEmployee(ids);
        return ResponseUtil.success();
    }


}